package com.snail.manager.user.service;


import com.snail.manager.user.Exception.UserUnAvtiveException;
import com.snail.manager.user.entity.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Service
public class ShiroRealm extends AuthenticatingRealm{

    @Autowired
    private LoginService loginService;

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws UnknownAccountException, UserUnAvtiveException {
       //把AuthenticationToken转换为UsernamePasswordToken
        System.out.println("验证.....................");
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;

        //2.从UsernamePasswordToken中获取username
        String username= upToken.getUsername();
        //3.调用数据库的方法，从数据库中获取username对应的记录


         User user = loginService.getUserByUsername(username);
        //System.out.printf("_________________"+user.getState());

        //若用户不存在，抛出UnkownAccountException
        if (user==null){
            throw new UnknownAccountException("用户不存在");
        }

        if (user.getState()==false){
            throw new UserUnAvtiveException("该账号未激活！");
        }
        //5.根据用户信息，决定是否抛出其他的AuthenticationException
        //5.根据用户情况，来构建AuthenticationInfo对象并返回Name
       Object principle = username;
       Object credentials =  user.getPassword();
        String realmnName = getName();
        ByteSource credentialsSalt = ByteSource.Util.bytes(username);
        SimpleAuthenticationInfo simpleAuthenticationInfo = null;//new SimpleAuthenticationInfo(principle,credentials,realmnName);
        simpleAuthenticationInfo = new SimpleAuthenticationInfo(principle,credentials,credentialsSalt,realmnName);//盐值加密

        return simpleAuthenticationInfo;
    }

    public static void main(String[] args) {
        Object result = new SimpleHash("MD5","123",null,1);
        System.out.println(result);
    }
}
